package com.gitee.mars.studyabroad.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.mars.studyabroad.constant.Constant;
import com.gitee.mars.studyabroad.constant.DefaultAvatar;
import com.gitee.mars.studyabroad.entity.User;
import com.gitee.mars.studyabroad.exception.WorkException;
import com.gitee.mars.studyabroad.mapper.UserMapper;
import com.gitee.mars.studyabroad.request.UserRequest;
import com.gitee.mars.studyabroad.response.UserResponse;
import com.gitee.mars.studyabroad.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;


/**
 * User 实现层
 *
 * @Author wq
 * @Date 2021-03-16
 **/
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Override
    public UserResponse login(UserRequest request) {

        if (StringUtils.isEmpty(request.getMobile())) {
            throw new WorkException("请输入账号");
        }
        User user = baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getMobile, request.getMobile()));
        if (Objects.isNull(user)) {
            return register(request);
        } else {
            if (request.getPassword().equals(user.getPassword())) {
                UserResponse userResponse = new UserResponse();
                userResponse.setUserId(user.getId());
                userResponse.setNickname(user.getNickname());
                userResponse.setAvatar(user.getAvatar());
                return userResponse;
            }
        }
        return null;
    }

    @Override
    public UserResponse register(UserRequest request) {
        User user = baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getMobile, request.getMobile()));
        if (Objects.nonNull(user)) {
            throw new WorkException("该账号已注册,请直接登录");
        }
        User user1 = new User();
        user1.setAvatar(DefaultAvatar.getUserAvatar());
        user1.setNickname("用户_" + request.getMobile().substring(7));
        user1.setPassword(request.getPassword());
        user1.setCreateTime(new Date());
        user1.setStatus(Constant.ONE);
        user1.setGender(Constant.ONE);
        user1.setMobile(request.getMobile());
        user1.setUpdateTime(new Date());
        save(user1);
        UserResponse userResponse = new UserResponse();
        userResponse.setUserId(user1.getId());
        userResponse.setNickname(user1.getNickname());
        userResponse.setAvatar(user1.getAvatar());
        return userResponse;
    }
}